<template>
  <div class="partNumberUpoadImg">
    <div class="cardCon">
      <van-form @submit="formSubmitted" ref="form">
        <van-field
          v-model="form.orderNo"
          name="orderNo"
          label="料号"
          placeholder="料号"
          class="orderNo"
          :rules="[{ required: true, message: '请填写料号' }]"
          @change="orderNoChange"
        ></van-field>
        <van-field
          v-model="form.productName"
          name="productName"
          label="品名"
          placeholder="品名"
          readonly
        ></van-field>
        <van-field
          v-model="form.specifications"
          name="specifications"
          label="规格"
          placeholder="规格"
          readonly
        ></van-field>
        <van-field
          name="uploader"
          label="上传文件"
          :rules="[{ validator: uploadValidator, message: '请上传文件' }]"
        >
          <template #input>
            <van-uploader
              v-model="fileList"
              accept=".pdf"
              :max-count="30"
              :multiple="true"
              :max-size="1024 * 1024 * 200"
              :before-delete="beforeDelete"
              upload-icon="description"
              @click-preview="clickPreview"
              @oversize="uploadOversize"
            />
          </template>
        </van-field>
      </van-form>
      <div class="btnCon">
        <van-button
          class="opeBtn"
          type="info"
          :disabled="!canSend"
          round
          @click="submitClick"
          >提交</van-button
        >
      </div>
    </div>
  </div>
</template>

<script>
import { mapActions, mapMutations } from "vuex";
import { Form, Field, Toast, Dialog, Uploader, Button, Icon } from "vant";
let reg = /(.*?)\.(png|jpe?g|gif|bmp|psd|tiff|tga|eps|PNG|JPE?G|GIF)/;
export default {
  components: {
    [Form.name]: Form,
    [Field.name]: Field,
    [Uploader.name]: Uploader,
    [Button.name]: Button,
    [Icon.name]: Icon,
  },
  data() {
    return {
      pageReady: true,
      scaneClick: false,
      form: {
        orderNo: "",
        name: [],
        productName: "",
        specifications: "",
      },
      fileList: [],
      canSend: false,
    };
  },
  methods: {
    ...mapActions({
      getWxWorkJsApiConfig: "sys/getWxWorkJsApiConfig",
      uploadImg: "t100/uploadImg",
      uploadImgApi: "t100/uploadImgApi",
    }),
    uploadValidator(val) {
      if (this.fileList.length < 1) {
        return false;
      }
      return true;
    },
    uploadOversize() {
      Toast("文件大小不能超过200M");
    },
    beforeDelete(e) {
      console.log(e);
      if (e.file) {
        return true;
      } else {
        Dialog.alert({
          title: "提示",
          message: "已上传的文件请到T100中删除",
        }).then(() => {
          // on close
        });
        return false;
      }
    },
    clickPreview(e) {
      console.log(e);
      let pre = `${process.env.VUE_APP_T100_API}${process.env.VUE_APP_T100_PIC}/${this.form.orderNo}/`;
      if (e.file && e.file.type.includes("pdf")) {
        let url = URL.createObjectURL(e.file);
        window.open(url);
      } else if (e.url && e.url.includes("pdf")) {
        window.open(pre + e.url);
      }
    },
    orderNoChange() {
      if (this.form.orderNo) {
        this.getOrderInfo(this.form.orderNo);
      } else {
        this.initForm("");
      }
    },
    initForm(orderNo) {
      this.form.name = [];
      this.form.orderNo = orderNo || "";
      this.fileList = [];
      this.form.specifications = "";
      this.form.productName = "";
    },
    getOrderInfo(orderNo) {
      console.log("getOrderInfo", orderNo);
      this.scaneClick = false;
      this.handleT100Api(2)
        .then((res) => {
          console.log(res);
          this.fileList = [];
          this.form.name = [];
          if (res && res.success) {
            this.canSend = true;
            if (res.data.data) {
              let arr = res.data.data;
              if (arr && Array.isArray(arr)) {
                arr.forEach((e) => {
                  if (reg.test(e.NAME)) {
                    this.fileList.push({
                      url: `${process.env.VUE_APP_T100_API}${process.env.VUE_APP_T100_PIC}/${orderNo}/${e.NAME}`,
                    });
                  } else {
                    this.fileList.push({
                      url: `${e.NAME}`,
                    });
                  }
                });
              }
            }
            if (res.data.imaal003) {
              this.form.productName = res.data.imaal003;
            }
            if (res.data.imaal004) {
              this.form.specifications = res.data.imaal004;
            }
          } else {
            this.canSend = false;
            this.initForm(orderNo);
            Dialog.alert({
              title: "提示",
              message: res.message,
            }).then(() => {
              // on close
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    handleUploadImg() {
      return new Promise((resolve, reject) => {
        let sendData = {
          params: {
            orderNo: this.form.orderNo,
          },
        };
        let fd = new FormData();
        let flag = false;
        this.fileList.forEach((e) => {
          if (e.file) {
            fd.append("attach", e.file);
            flag = true;
          }
        });
        sendData.fd = fd;
        if (flag) {
          this.uploadImg(sendData)
            .then((res) => {
              console.log(res);
              if (res && res.errno == 0) {
                if (res.data && res.data.length > 0) {
                  res.data.forEach((e) => {
                    this.form.name.push({
                      picname: `${e}`,
                    });
                  });
                }
                resolve();
              } else {
                reject("上传图片失败");
              }
            })
            .catch((err) => {
              console.log(err);
              reject(err);
            });
        } else {
          resolve();
        }
      });
    },
    handleT100Api(type) {
      return new Promise((resolve, reject) => {
        let sendData = {
          type,
          no: this.form.orderNo,
          flag: "imaa",
        };
        if (type == 1) {
          let nameArr = this.form.name.map((e) => {
            return {
              picname: `${process.env.VUE_APP_T100_REALDIR}${process.env.VUE_APP_T100_PIC}${e.picname}`,
            };
          });
          sendData.name = JSON.stringify(nameArr);
        }
        this.uploadImgApi(sendData)
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            console.log(err);
            reject(err);
          });
      });
    },
    submitClick() {
      this.$refs.form.submit();
    },
    formSubmitted() {
      Toast.loading({
        message: "上传中...",
        forbidClick: true,
        loadingType: "spinner",
      });
      this.handleUploadImg()
        .then(() => {
          return this.handleT100Api(1);
        })
        .then((res) => {
          console.log(res);
          if (res && res.success) {
            Toast.success("操作成功");
            this.getOrderInfo(this.form.orderNo);
          } else {
            Toast.fail(`操作失败:${res.message}`);
          }
        })
        .catch((err) => {
          Toast.fail(err);
        });
    },
  },
};
</script>

<style lang="scss">
.partNumberUpoadImg {
  padding: 24px;
  .cardCon {
    padding: 24px;
    background-color: white;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    border: 1px solid #ebeef5;
  }
  .btnCon {
    text-align: center;
    .opeBtn {
      width: 200px;
    }
  }
  .van-uploader__file,
  .van-uploader__upload,
  .van-uploader__preview-image {
    width: 120px;
    height: 120px;
  }
  .van-uploader__file-icon,
  .van-uploader__upload-icon {
    font-size: 36px;
  }
}
</style>